package com.sf.web.controller;

import com.sf.domain.Department;
import com.sf.service.IDepartmentService;
import com.sf.util.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@CrossOrigin
public class DepartmentController {
    @Autowired
    private IDepartmentService departmentService;
    /**
     * /department/list
     * {success: true,msg: 操作成功, data: List}
     */
    @RequestMapping("/department/list")
    @ResponseBody
    public JsonResult list() {
        return new JsonResult(true, "操作成功", departmentService.list());
    }

    @RequestMapping("/department/delete")
    @ResponseBody
    public JsonResult delete(Long id) {
//        int i = 1 / 0;
        departmentService.delete(id);
        return new JsonResult(true, "操作成功", null);
    }

    @RequestMapping("/department/save")
    @ResponseBody
    public JsonResult save(@RequestBody Department department){
        departmentService.save(department);
        return new JsonResult(true,"操作成功",null);
    }

    @RequestMapping("/department/update")
    @ResponseBody
    public JsonResult update(@RequestBody Department department) {
        try {
            // 简单参数校验
            if (department.getId() == null) {
                return new JsonResult(false, "更新失败: 部门ID不能为空", null);
            }
            departmentService.update(department);
            return new JsonResult(true, "更新成功", null);
        } catch (Exception e) {
            // 捕获服务层抛出的异常并返回给前端
            return new JsonResult(false, "更新失败: " + e.getMessage(), null);
        }
    }

}
